package com.gzdh.dishrecognition;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.dk.bleNfc.BleManager.Scanner;
import com.dk.bleNfc.BleNfcDeviceService;
import com.dk.bleNfc.DeviceManager.BleHelper;
import com.dk.bleNfc.DeviceManager.BleNfcDevice;
import com.dk.bleNfc.DeviceManager.BluetoothHelper;
import com.gzdh.dishrecognition.config.ProductConst;
import com.gzdh.dishrecognition.config.SysConstConfig;
import com.greendao.dao.MacMainpSbruanDinnerEntityDao;
import com.gzdh.dishrecognition.emu.ModelEmus;
import com.gzdh.dishrecognition.emu.OfflineGetCardSnTypeEmus;
import com.gzdh.dishrecognition.emu.PeripheralDeviceEmus;
import com.gzdh.dishrecognition.entity.MacMainpSbruanDinnerEntity;
import com.gzdh.dishrecognition.event.CartEvent;
import com.gzdh.dishrecognition.event.FoodsCard;
import com.gzdh.dishrecognition.event.RefEvent;
import com.gzdh.dishrecognition.event.TimeEvent;
import com.gzdh.dishrecognition.ui.activity.LoginActivity;
import com.gzdh.dishrecognition.ui.activity.ReportActivity;
import com.gzdh.dishrecognition.ui.activity.SysInfoActivity;
import com.gzdh.dishrecognition.ui.activity.SysMenuActivity;
import com.gzdh.dishrecognition.ui.activity.UnOnLineActivity;
import com.gzdh.dishrecognition.ui.activity.jiaobanActivity;
import com.gzdh.dishrecognition.ui.adapter.LeftBmcmAdapter;
import com.gzdh.dishrecognition.ui.base.BaseMVCActivity;
import com.gzdh.dishrecognition.ui.pre.CardInfoPre;
import com.gzdh.dishrecognition.ui.pre.DefaultMainPre;
import com.gzdh.dishrecognition.ui.pre.ProductPre;
import com.gzdh.dishrecognition.ui.pre.ShowCardPre;
import com.gzdh.dishrecognition.ui.view.DefaultModelView;
import com.gzdh.dishrecognition.ui.view.FixedNumberView;
import com.gzdh.dishrecognition.ui.view.IdfModelView;
import com.gzdh.dishrecognition.ui.view.InputNumberView;
import com.gzdh.dishrecognition.ui.view.OptionItemView;
import com.gzdh.dishrecognition.util.ByteUtil;
import com.gzdh.dishrecognition.util.DateUtil;
import com.gzdh.dishrecognition.util.ProductSUtils;
import com.gzdh.dishrecognition.util.ScanKeyManager;
import com.gzdh.dishrecognition.util.SystemUtils;
import com.gzdh.dishrecognition.util.TripleDESUtil;
import com.jiebao.nfc.uartnfc.CardReaderDevice;
import com.serialport.JBScanner;
import com.slidingmenu.lib.SlidingMenu;

import net.posprinter.posprinterface.IMyBinder;
import net.posprinter.posprinterface.TaskCallback;
import net.posprinter.service.PosprinterService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class MainActivity extends BaseMVCActivity {

    private DefaultMainPre defaultMainPre;

    private ProductPre productPre;

    private ShowCardPre showCardPre;

    private CardInfoPre cardInfoPre;

    private SlidingMenu slidingMenu;

    private boolean hideDinner;

    private RecyclerView recyclerView;


    private MacMainpSbruanDinnerEntityDao macMainpSbruanDinnerEntityDao;

    private DefaultModelView defaultModelView;

    private InputNumberView inputNumberView;

    private FixedNumberView fixedNumberView;

    private IdfModelView idfModelView;


    BleNfcDeviceService mBleNfcDeviceService;
    private BleNfcDevice bleNfcDevice;
    private Scanner mScanner;


    private JBScanner scanner;

    private ScanKeyManager scanKeyManager;

    private BleHelper bleHelper;


    private StringBuffer msgBuffer = new StringBuffer();
    private BluetoothDevice mNearestBle = null;
    private Lock mNearestBleLock = new ReentrantLock();// 锁对象
    private int lastRssi = -100;
    private CharSequence[] items = null;
    private boolean isBind = false;
    private int bleCacheNum = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        hideDinner = SysConstConfig.getInstance().isHideDinner();
        macMainpSbruanDinnerEntityDao = AppContext.getInstance().getDaoSession().getMacMainpSbruanDinnerEntityDao();
        defaultModelView = findViewById(R.id.defaultModelView);
        inputNumberView = findViewById(R.id.inputNumberView);
        fixedNumberView = findViewById(R.id.fixedNumberView);
        idfModelView = findViewById(R.id.idfModelView);
        DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
        if (SysConstConfig.getInstance().isHideDinner()) {
            slidingMenu = new SlidingMenu(this);
            slidingMenu.setMode(SlidingMenu.LEFT_RIGHT);
            View view = View.inflate(this, R.layout.menu_left_layout, null);
            slidingMenu.setMenu(view);
            slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
            slidingMenu.setFadeEnabled(true);
            initSlidingMenuButton(view);  //向右滑页面内容
            View view2 = View.inflate(this, R.layout.menu_right_layout, null);
            initSlidingMenuButtonRight(view2);
            slidingMenu.setSecondaryMenu(view2);
            slidingMenu.setShadowWidth(getWindowManager().getDefaultDisplay().getWidth() / 700);
            slidingMenu.setBehindOffset((displayMetrics.widthPixels - dp2px(300)));
//            slidingMenu.setBehindOffsetRes(R.dimen.sliding_menu_offset);//设置偏离距离
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);//全屏模式，全屏滑动都可打开
        } else {
            slidingMenu = new SlidingMenu(this);
            slidingMenu.setMode(SlidingMenu.RIGHT);
            slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
            slidingMenu.setFadeEnabled(true);
            View view2 = View.inflate(this, R.layout.menu_right_layout, null);
            initSlidingMenuButtonRight(view2);
            slidingMenu.setShadowWidth(getWindowManager().getDefaultDisplay().getWidth() / 700);
//            slidingMenu.setBehindOffsetRes(R.dimen.sliding_menu_offset);//设置偏离距离
            slidingMenu.setBehindOffset((displayMetrics.widthPixels - dp2px(300)));
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);//全屏模式，全屏滑动都可打开
            slidingMenu.setMenu(view2);
        }
        if (defaultModelView != null) {
            defaultModelView.setBleNfcClick(() -> {
                if (mBleNfcDeviceService != null) {
                    mBleNfcDeviceService.startScanAndConnectTheNearestDevice();
                }
            });
        }

        Intent intent = new Intent(this, PosprinterService.class);
        isBind = bindService(intent, mSerconnection, BIND_AUTO_CREATE);
        if (SysConstConfig.getInstance().getPeripheralDeviceModel() == PeripheralDeviceEmus.cloudQrAndReadCard) {
            System.out.println("云设备");
            scanKeyManager = new ScanKeyManager((String value) -> {
                Log.i("MainActivity", "ScanValue->" + value);
                if (SysConstConfig.getInstance().getOfflineGetCardSnType() == OfflineGetCardSnTypeEmus.direct) {
                    runOnUiThread(() -> defaultModelView.getCardInfo(value));
                } else {
                    byte[] cardSnTemp = ByteUtil.hexStringToByte(value.toUpperCase());
                    byte[] cardSn = new byte[4];
                    for (int i = 0; i < cardSnTemp.length; i++) {
                        cardSn[i] = cardSnTemp[3 - i];
                    }
                    runOnUiThread(() -> defaultModelView.getCardInfo(ByteUtil.bytesToHexString(cardSn)));
                }
            });
        }
    }

    @SuppressLint("SetTextI18n")
    public void init() {
        if (SysConstConfig.getInstance().isAllowCard()) {
            if (SysConstConfig.getInstance().getPeripheralDeviceModel() == PeripheralDeviceEmus.defaultType) {
                CardReaderDevice.getInstance().initCardReader();
            }
        }
        if (SysConstConfig.getInstance().getPeripheralDeviceModel() == PeripheralDeviceEmus.cloudQrAndReadCard) {
            System.out.println("云设备");
            scanKeyManager = new ScanKeyManager((String value) -> {
                Log.i("MainActivity", "ScanValue->" + value);
                if (SysConstConfig.getInstance().getOfflineGetCardSnType() == OfflineGetCardSnTypeEmus.direct) {
                    runOnUiThread(() -> defaultModelView.getCardInfo(value));
                } else {
                    byte[] cardSnTemp = ByteUtil.hexStringToByte(value.toUpperCase());
                    byte[] cardSn = new byte[4];
                    for (int i = 0; i < cardSnTemp.length; i++) {
                        cardSn[i] = cardSnTemp[3 - i];
                    }
                    runOnUiThread(() -> defaultModelView.getCardInfo(ByteUtil.bytesToHexString(cardSn)));
                }
            });
        } else {
            scanKeyManager = null;
        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(TimeEvent event) {
        try {
            String code = CardReaderDevice.getInstance().readCardNo();
            if (code == null || "".equals(code)) {
                return;
            }
            /*if(!SystemUtils.checkCard(this, code)) {
                return;
            }*/
            if (SysConstConfig.getInstance().getOfflineGetCardSnType() == OfflineGetCardSnTypeEmus.direct) {
                runOnUiThread(() -> defaultModelView.getCardInfo(code));
            } else {
                byte[] cardSnTemp = ByteUtil.hexStringToByte(code.toUpperCase());
                byte[] cardSn = new byte[4];
                for (int i = 0; i < cardSnTemp.length; i++) {
                    cardSn[i] = cardSnTemp[3 - i];
                }
                runOnUiThread(() -> defaultModelView.getCardInfo(ByteUtil.bytesToHexString(cardSn)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int dp2px(final float dpValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (SysConstConfig.getInstance().isHideDinner() != hideDinner) {
            this.recreate();
        }
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        defaultModelView.resShow();
        if (ProductConst.getInstance().getProductCartModelList().size() > 0) {
            if (SysConstConfig.getInstance().getSurfaceModel() != ModelEmus.numberType &&
                    (inputNumberView == null || inputNumberView.getVisibility() == View.GONE) &&
                    (fixedNumberView == null || fixedNumberView.getVisibility() == View.GONE)) {
                defaultMainPre.hide();
                showPresentation(productPre);
                if(productPre != null) {
                    productPre.show();
                    productPre.showData();
                }
            }

        } else {
            showPresentation(defaultMainPre);
            if(defaultMainPre != null) {
                defaultMainPre.show();
            }
            if(productPre != null) {
                productPre.hide();
                productPre.clear();
            }
        }
        MacMainpSbruanDinnerEntity macMainpSbruanDinnerEntity = getDinner();
        if (macMainpSbruanDinnerEntity != null &&
                !macMainpSbruanDinnerEntity.getDinner().equals(ProductConst.getInstance().getBmcm())) {
            ProductConst.getInstance().setBmcm(macMainpSbruanDinnerEntity.getDinner());
            defaultModelView.selectBmcm(macMainpSbruanDinnerEntity);
        }
        switch (SysConstConfig.getInstance().getSurfaceModel()) {
            case defaultType:
                defaultModelView.setVisibility(View.VISIBLE);
                inputNumberView.setVisibility(View.GONE);
                inputNumberView.close();
                fixedNumberView.setVisibility(View.GONE);
                fixedNumberView.close();
                idfModelView.setVisibility(View.GONE);
                defaultModelView.loadFoodsMenu();
                break;
            case numberType:
                inputNumberView.setVisibility(View.VISIBLE);
                inputNumberView.init();
                fixedNumberView.setVisibility(View.GONE);
                fixedNumberView.close();
                defaultModelView.setVisibility(View.GONE);
                idfModelView.setVisibility(View.GONE);
                break;
            case fixedType:
                fixedNumberView.setVisibility(View.VISIBLE);
                fixedNumberView.init();
                inputNumberView.setVisibility(View.GONE);
                inputNumberView.close();
                defaultModelView.setVisibility(View.GONE);
                idfModelView.setVisibility(View.GONE);
                break;
            case idfType:
                inputNumberView.setVisibility(View.GONE);
                inputNumberView.close();
                fixedNumberView.setVisibility(View.GONE);
                fixedNumberView.close();
                defaultModelView.setVisibility(View.GONE);
                idfModelView.setVisibility(View.VISIBLE);
                if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    ActivityCompat.requestPermissions(mActivity,
                            new String[]{android.Manifest.permission.CAMERA}, 100);
                    return;
                }
                idfModelView.onStart();
        }
        if (showCardPre != null && showCardPre.isShowing()) {
            showCardPre.hide();
        }
        inputNumberView.setShowCardPre(showCardPre);
        if (cardInfoPre != null && cardInfoPre.isShowing()) {
            cardInfoPre.hide();
        }
        defaultModelView.setCardInfoPre(cardInfoPre);
        checkNetStateThread();
        init();
        syncServerTimeThread();
    }

    // 在你的 Activity 中，比如 onCreate() 中调用
    private static final int REQUEST_BLUETOOTH_PERMISSIONS = 1001;

    private void checkAndRequestBluetoothPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 12 (API 31) 及以上，使用新的蓝牙权限
            String[] requiredPermissions = new String[]{
                    android.Manifest.permission.BLUETOOTH_SCAN,
                    android.Manifest.permission.BLUETOOTH_CONNECT,
                    android.Manifest.permission.ACCESS_FINE_LOCATION
            };

            List<String> permissionsToRequest = new ArrayList<>();
            for (String perm : requiredPermissions) {
                if (checkSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
                    permissionsToRequest.add(perm);
                }
            }

            if (!permissionsToRequest.isEmpty()) {
                requestPermissions(permissionsToRequest.toArray(new String[0]), REQUEST_BLUETOOTH_PERMISSIONS);
                return;
            }
        } else {
            // Android 11 及以下，主要需要定位权限
            if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_BLUETOOTH_PERMISSIONS);
                return;
            }
        }
        // 所有权限已经有了，可以开始使用 BluetoothHelper
        onBluetoothPermissionsGranted();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_BLUETOOTH_PERMISSIONS) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            if (allGranted) {
                onBluetoothPermissionsGranted();
            } else {
                Toast.makeText(this, "需要蓝牙和定位权限才能使用该功能", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void onBluetoothPermissionsGranted() {
        // 权限已经 OK，可以安全地初始化并使用 BleHelper 了！
        Log.d("MainActivity", "蓝牙权限已获取，可以开始扫描或连接");
        bleHelper = new BleHelper(this);
        bleHelper.addListener(new BleHelper.BLEListener() {
            @Override
            public void onBluetoothReady() {
                //Log.d("BLE", "蓝牙就绪，开始扫描");
                bleHelper.startScan();
            }

            @Override
            public void onDeviceFound(BluetoothDevice device) {
                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                Log.d("BLE", "发现设备: " + device.getName() + " / " + device.getAddress());
            }

            @Override
            public void onDeviceConnected() {
                Log.d("BLE", "BLE 设备连接成功");
                // 可以开始通信，比如发送数据：bleHelper.writeData("Hello".getBytes());
            }

            @Override
            public void onDeviceDisconnected() {
                Log.d("BLE", "BLE 设备断开");
            }

            @Override
            public void onServicesDiscovered() {
                Log.d("BLE", "服务发现完成，可以读写特征了");
            }

            @Override
            public void onDataReceived(byte[] data) {
                StringBuilder received = new StringBuilder();
                for (byte b : data) {
                    received.append(String.format("%02X", b));
                }
                Log.d("BLE", "收到数据: " + received);
                if("000000".equals(received.toString())) {
                    return;
                }
                ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                List<ActivityManager.AppTask> tasks = am.getAppTasks();
                if (!tasks.isEmpty()) {
                    ComponentName topActivity = tasks.get(0).getTaskInfo().topActivity;
                    String activityName = topActivity.getClassName();
                    if(!"com.gzdh.dishrecognition.MainActivity".equals(activityName)) {
                        return;
                    }
                }
                if("3B0000".equals(received.toString())) {
                    bleCacheNum = 20;
                    return;
                }
                if("3D0000".equals(received.toString())) {
                    defaultModelView.confirmClick();
                    return;
                }
                if("3E0000".equals(received.toString())) {
                    defaultModelView.cancelClick();
                    return;
                }
                Integer num = SystemUtils.getBleKeyCode(received.toString());
                if(bleCacheNum != 0) {
                    num = bleCacheNum + num;
                    bleCacheNum = 0;
                }
                onEvent(new FoodsCard(num));
            }

            @Override
            public void onError(String message) {
                Log.e("BLE", "错误: " + message);
            }
        });
        bleHelper.startScan();
    }


    @Override
    protected void initData() {
        //Intent gattServiceIntent = new Intent(this, BleNfcDeviceService.class);
        //bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        checkAndRequestBluetoothPermissions();
    }

    private MacMainpSbruanDinnerEntity getDinner() {
        String hourMin = new SimpleDateFormat("HH:mm").format(new Date());
        try {
            List<MacMainpSbruanDinnerEntity> macMainpSbruanDinnerList = macMainpSbruanDinnerEntityDao.loadAll();
            for (MacMainpSbruanDinnerEntity goo : macMainpSbruanDinnerList) {
                if (DateUtil.hourMinuteBetween(hourMin, goo.getStartTime(), goo.getEndTime())) {
                    return goo;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void dissmissPresnetation() {
        if(defaultMainPre != null) {
            defaultMainPre.dismiss();
        }
    }


    @Override
    public void initPresentation() {
        super.initPresentation();
        if (mDisplay != null) {
            defaultMainPre = new DefaultMainPre(MainActivity.this, mDisplay);
            productPre = new ProductPre(MainActivity.this, mDisplay);
            showCardPre = new ShowCardPre(MainActivity.this, mDisplay);
            cardInfoPre = new CardInfoPre(MainActivity.this, mDisplay);
            registerPresentation(cardInfoPre);
            registerPresentation(defaultMainPre);
            showPresentation(defaultMainPre);
            registerPresentation(productPre);
            if(defaultMainPre != null) {
                defaultMainPre.show();
            }
        }
    }

    private void initSlidingMenuButtonRight(View view) {
        view.findViewById(R.id.setting_but).setOnClickListener(view1 -> {
            SysMenuActivity.start(mActivity);
        });
        view.findViewById(R.id.sysInfoBut).setOnClickListener(view1 -> {
            SysInfoActivity.start(mActivity);
        });
        view.findViewById(R.id.unOnlineOrderBut).setOnClickListener(view1 -> {
            UnOnLineActivity.start(mActivity);
        });
        view.findViewById(R.id.reportBut).setOnClickListener(view1 -> {
            ReportActivity.start(mActivity);
        });
        OptionItemView onLineBut = view.findViewById(R.id.onLineBut);
        if (SysConstConfig.getInstance().isOnLinePay()) {
            onLineBut.setRightText("开启");
        } else {
            onLineBut.setRightText("关闭");
        }
        view.findViewById(R.id.logoutBut).setOnClickListener(view1 -> {
            SharedPreferences sysCost = getSharedPreferences("sysCost", MODE_PRIVATE);
            SharedPreferences.Editor editor = sysCost.edit();
            editor.putString("user", "");
            editor.apply();
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        });
        onLineBut.setOnClickListener(view1 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
            builder.setTitle("脱机消费");
            final Map<String, Boolean> map = new LinkedHashMap<>();
            map.put("开启", true);
            map.put("关闭", false);
            final String[] keysTemp = new String[2];
            final String[] keys = map.keySet().toArray(keysTemp);
            builder.setItems(keys, (dialog, which) -> {
                boolean state = map.get(keys[which]);
                SysConstConfig.getInstance().setOnLinePay(state);
                onLineBut.setRightText(keys[which]);
            });
            builder.show();
        });
        view.findViewById(R.id.calcBut).setOnClickListener(view1 -> {
            switch (SysConstConfig.getInstance().getSurfaceModel()) {
                case defaultType:
                    inputNumberView.setVisibility(View.VISIBLE);
                    defaultModelView.setVisibility(View.GONE);
                    fixedNumberView.setVisibility(View.GONE);
                    inputNumberView.init();
                    SysConstConfig.getInstance().setSurfaceModel(ModelEmus.numberType);
                    break;
                case numberType:
                    fixedNumberView.setVisibility(View.VISIBLE);
                    defaultModelView.setVisibility(View.GONE);
                    inputNumberView.setVisibility(View.GONE);
                    fixedNumberView.init();
                    SysConstConfig.getInstance().setSurfaceModel(ModelEmus.fixedType);
                    break;
                case fixedType:
                    defaultModelView.setVisibility(View.VISIBLE);
                    inputNumberView.setVisibility(View.GONE);
                    fixedNumberView.setVisibility(View.GONE);
                    ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
                    onEvent(new CartEvent());
                    SysConstConfig.getInstance().setSurfaceModel(ModelEmus.defaultType);
                    break;
            }
            /*if (defaultModelView.getVisibility() == View.GONE && inputNumberView.getVisibility() == View.VISIBLE) {
                defaultModelView.setVisibility(View.VISIBLE);
                inputNumberView.setVisibility(View.GONE);
                ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
                onEvent(new CartEvent());
            } else if (defaultModelView.getVisibility() == View.VISIBLE && inputNumberView.getVisibility() == View.GONE) {
                inputNumberView.setVisibility(View.VISIBLE);
                inputNumberView.init();
                defaultModelView.setVisibility(View.GONE);
            }*/
        });
        view.findViewById(R.id.jiaobanBut).setOnClickListener(view1 -> startActivity(new Intent(mContext, jiaobanActivity.class)));
        OptionItemView currentPosBut = view.findViewById(R.id.currentPosBut);
        currentPosBut.setRightText(SysConstConfig.getInstance().getPos());
        OptionItemView currentVersionBut = view.findViewById(R.id.currentVersionBut);
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            currentVersionBut.setRightText(packageInfo.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            currentVersionBut.setRightText("");
        }

    }

    private void initSlidingMenuButton(View view) {
        recyclerView = view.findViewById(R.id.recyclerView);
        LeftBmcmAdapter leftBmcmAdapter = new LeftBmcmAdapter(mActivity);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(leftBmcmAdapter);
        List<MacMainpSbruanDinnerEntity> macMainpSbruanDinnerEntityList = macMainpSbruanDinnerEntityDao.loadAll();
        ProductSUtils.setSbruanDinnerName(macMainpSbruanDinnerEntityList);
        leftBmcmAdapter.setList(macMainpSbruanDinnerEntityList);
        leftBmcmAdapter.setUserOnClick(bmcmEntity -> {
            defaultModelView.selectBmcm(bmcmEntity);
            slidingMenu.toggle();
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CartEvent event) {
        defaultModelView.resShow();
        inputNumberView.resShow();
        if (ProductConst.getInstance().getProductCartModelList().size() > 0) {
            if (SysConstConfig.getInstance().getSurfaceModel() != ModelEmus.numberType &&
                    (inputNumberView == null || inputNumberView.getVisibility() == View.GONE) &&
                    (fixedNumberView == null || fixedNumberView.getVisibility() == View.GONE)) {
                showPresentation(productPre);
                if(defaultMainPre != null) {
                    defaultMainPre.hide();
                }
                if(productPre != null) {
                    productPre.show();
                    productPre.showData();
                }
            }
        } else {
            showPresentation(defaultMainPre);
            if (defaultMainPre != null) {
                defaultMainPre.show();
            }
            if(productPre != null) {
                productPre.hide();
                productPre.clear();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefEvent event) {
        showPresentation(cardInfoPre);
        if(cardInfoPre != null) {
            cardInfoPre.show();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(FoodsCard event) {
        System.out.println("菜号：" + event.getId());
        if (defaultModelView != null && defaultModelView.getVisibility() == View.VISIBLE) {
            defaultModelView.foodCard(event.getId());

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 适当生命周期中停止扫描和断开连接
        bleHelper.stopScan();
        bleHelper.disconnect();
        /*if(isBind && mBleNfcDeviceService != null) {
            unbindService(mServiceConnection);
            isBind = false;
        }*/
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            if(scanKeyManager != null) {
                scanKeyManager.analysisKeyEvent(event);
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    //隐藏软键盘
    //在activity里面重写  dispatchTouchEvent
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }


    /**
     * 是否隐藏键盘
     */
    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            // 点击的是输入框区域，保留点击EditText的事件
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        return false;
    }


    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBleNfcDeviceService = ((BleNfcDeviceService.LocalBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBleNfcDeviceService = null;
        }
    };

    private Context mContext;
    private UsbManager mUsbManager;
    private UsbDeviceConnection mUsbDeviceConnection;
    private UsbEndpoint ep, printerEp;
    private PendingIntent mPermissionIntent;
    private UsbInterface usbInterface;
    public static final String ACTION_USB_PERMISSION = "com.usb.printer.USB_PERMISSION";


    private void initUsb() {
        mContext = this;
        mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
        // 注册广播监听usb设备
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        mContext.registerReceiver(mUsbDeviceReceiver, filter);
        // 列出所有的USB设备，并且都请求获取USB权限
        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
        for (UsbDevice device : deviceList.values()) {
            // 得到此设备的一个接口
            usbInterface = device.getInterface(0);
            if (usbInterface.getInterfaceClass() == 7) {
                connectUSBPrint(device.getDeviceName());
            }
        }

    }


    private final BroadcastReceiver mUsbDeviceReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e("action", action);
            UsbDevice mUsbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false) && mUsbDevice != null) {
                        Log.e("receiver", action + "   " + mUsbDevice.toString());

                    } else {
//                        Toast.makeText(context, "USB设备请求被拒绝", Toast.LENGTH_SHORT).show();
//                        mInstance = null;
                    }
                }
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action) || UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                if (mUsbDevice != null) {
                    HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
                    for (UsbDevice device : deviceList.values()) {
                        // 得到此设备的一个接口
                        usbInterface = device.getInterface(0);
                        if (usbInterface.getInterfaceClass() == 7) {
                            disConnect();
                            connectUSBPrint(device.getDeviceName());
                        }
                    }
                }
            }
        }
    };

    private void connectUSBPrint(String usbAddress) {
        myBinder.ConnectUsbPort(getApplicationContext(), usbAddress, new TaskCallback() {
            @Override
            public void OnSucceed() {
                ISCONNECT = true;
                Toast.makeText(mContext, "打印机连接成功", Toast.LENGTH_SHORT).show();
//                Toast.makeText(getApplicationContext(),getString(R.string.connect),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void OnFailed() {
                ISCONNECT = false;
//                Toast.makeText(getApplicationContext(),getString(R.string.discon),Toast.LENGTH_SHORT).show();
            }
        });
    }

    public static IMyBinder myBinder;
    public static boolean ISCONNECT = false;
    ServiceConnection mSerconnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (IMyBinder) service;
            Log.e("myBinder", "connect");
            initUsb();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("myBinder", "disconnect");
        }
    };


    private void disConnect() {
        if (ISCONNECT) {
            myBinder.DisconnectCurrentPort(new TaskCallback() {
                @Override
                public void OnSucceed() {
                    ISCONNECT = false;
                    Toast.makeText(getApplicationContext(), "打印机已断开", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void OnFailed() {
                    ISCONNECT = true;
                    Toast.makeText(getApplicationContext(), "disconnect failed", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    public void syncServerTimeThread(){
        new Thread(() -> {
            while (true) {
                RequestUtils.getServerTime(MainActivity.this, new MyObserverRes<>(MainActivity.this, false) {
                    @Override
                    public void onSuccess(String result) {
                        Intent intent = new Intent();
                        intent.setAction("com.oem.action.UPDATE_TIME");
                        intent.putExtra("time", Long.parseLong(result));
                        sendBroadcast(intent);
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {
                        Log.d("LoginActivity", errorMsg);
                    }
                });
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
    public void checkNetStateThread(){
        new Thread(() -> {
            while (true) {
                try {
                    if(mContext == null) {
                        continue;
                    }
                    //获得ConnectivityManager对象
                    ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
                    //获取所有网络连接的信息
                    Network[] networks = connMgr.getAllNetworks();
                    //通过循环将网络信息逐个取出来
                    boolean noNet = true;
                    for (Network network : networks) {
                        //获取ConnectivityManager对象对应的NetworkInfo对象
                        NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
                        if (networkInfo.isConnected()) {
                            noNet = false;
                            runOnUiThread(() -> {
                                defaultModelView.connectedNet();
                                inputNumberView.connectedNet();
                                fixedNumberView.connectedNet();
                            });
                        }
                    }
                    if(noNet) {
                        runOnUiThread(() -> {
                            defaultModelView.disConnectedNet();
                            inputNumberView.disConnectedNet();
                            fixedNumberView.disConnectedNet();
                        });
                    }
                    Thread.sleep(3000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}